package leetcode.code068;

import java.util.ArrayList;
import java.util.List;

public class Solution extends Solution068 {

	@Override
	public List<String> fullJustify(String[] words, int maxWidth) {
		int p1 = 0;
		int p2 = 0;
		int len = words.length;
		int size = 0;
		int blank = 0;
		List<String> result = new ArrayList<>();
		while (p1 <= len) {
			if (p1 != len && size + words[p1].length() + blank <= maxWidth) {
				size = size + words[p1].length();
				blank++;
				p1++;
			} else {
				StringBuffer sb = new StringBuffer();
				int space = maxWidth - size;
				if (blank > 0) {
					blank--;
				}
				int mod = 0;
				int div = 0;
				if (blank != 0) {
					div = space / blank;
					mod = space % blank;
				} else {
					div = space;
				}
				while (p2 < p1) {
					sb.append(words[p2]);
					if (p1 != len && space > 0) {
						for (int i = 0; i < div; i++) {
							sb.append(' ');
						}
						space = space - div;
						if (mod > 0) {
							sb.append(' ');
							mod--;
							space--;
						}
					} else if (p1 == len && p2 < len - 1) {
						sb.append(' ');
					}
					p2++;
				}
				if (p1 == len) {
					for (int i = 0; i < space - blank; i++) {
						sb.append(' ');
					}
					p1++;
				}
				result.add(sb.toString());
				size = 0;
				blank = 0;
			}
		}
		return result;
	}

	public static void main(String[] args) {
		Solution so = new Solution();
		so.debug1();
		so.debug2();
		so.debug3();
		so.debug4();
//		System.out.println(5 % 2);
	}

}
